# -*- coding: utf-8 -*-
#*******************************************************************************
#   
#   http://www.chuiyao.com/manhua/\d+/ 解析器
#
#*******************************************************************************
from base import *

tag='chuiyao'

#---------------------------- 验证模块 ----------------------------

# 每个解析模块都含有这个函数，用来判断链接是否符合该模块
def url_judgement(url):
    if re.match(r'http://www.chuiyao.com/manhua/\d+/',url):
        return valid_check(url)
    return False

# 根据内容检测是否可解析
def valid_check(url):
    print('{} catch {}'.format(tag,url))
    content=request_for(url,common_headers);
    if content:
        return get_loader(url)
    return False

# 下载器获取
def get_loader(url):
    return ChuiyaoLoader(url,ChuiyaoPageParser,ChuiyaoVolParser)

#---------------------------- 下载器 ----------------------------

class ChuiyaoLoader(ComicLoader):
    def __init__(self,url,comic_page_parser,comic_vol_parser):
        super().__init__(url,comic_page_parser,comic_vol_parser)
    
#---------------------------- 解析器 ----------------------------

class ChuiyaoPageParser(ComicPageParser):
    def __init__(self,comic):
        super().__init__(comic)
    def work(self,content):
        # title
        self.comic.title=re.compile(r'<h1>(.*?)</h1>').findall(content)[0]
        # description
        self.comic.description=re.compile(r'<p>(.*?)<br>',re.S|re.M).findall(content)[0]
        # cover
        cover_content=re.compile(r'<div class="info_cover">(.*?)</div>',re.S|re.M).findall(content)[0]
        self.comic.cover=re.compile(r'src="(.*?)"',re.S|re.M).findall(cover_content)[0]
        # vols
        urls_content=re.compile(r'<div class="plist pnormal" id="play_0">(.*?)</div>',re.S|re.M).findall(content)[0]
        self.feed(urls_content)
        self.comic.vols.reverse()
    def handle_starttag(self,tag,attrs):
        if tag=='a':
            infos=info_collect(attrs)
            self.comic.vols.append(InfoVol(infos['href'],infos['title']))

class ChuiyaoVolParser(ComicVolParser):
    def __init__(self):
        super().__init__()
    def work(self,content):
        js_content=re.compile(r'var qTcms_S_m_murl_e = "(.*?)";',re.S|re.M).findall(content)[0]
        dec_content=base64.b64decode(js_content).decode('utf-8')
        urls=dec_content.split('$qingtiandy$')
        for url in urls:
            self.pic_urls.append((url,zero_prefix(self.pic_index)))
            self.pic_index+=1